package com.joker.microstoremanager.controller;

import com.google.common.base.Strings;
import com.joker.common.model.JokerResponse;
import com.joker.microstoremanager.model.MicroShop;
import com.joker.microstoremanager.repository.ShopRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@Slf4j
@Controller
@RequestMapping("login")
public class MyLoginController {

    @Resource
    private ShopRepository shopRepository;

    @GetMapping()
    public ModelAndView LoginAction(@RequestParam Optional<String> error) {
        return new ModelAndView("login","error",error);
    }

    @RequestMapping(value = "success",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JokerResponse<String> loginSuccess(){
        return new JokerResponse<>("success");
    }

    @GetMapping("register")
    public ModelAndView register(){
        return new ModelAndView("register");
    }

    @GetMapping("forgetPass")
    public ModelAndView forgetPass(){
        return new ModelAndView("register");
    }

    @PostMapping("doRegist")
    @ResponseBody
    public JokerResponse<String> doRegist(MicroShop shop){
        JokerResponse<String> response = new JokerResponse<>();
        if(Strings.isNullOrEmpty(shop.getPassword())){
            response.setMessage("请填写密码！");
            return response;
        }
        MicroShop user = shopRepository.findByUsername(shop.getUsername());
        if(user!=null){
            response.setMessage("该邮箱已被占用，请直接登陆或者使用新的邮箱注册！");
            return response;
        }
        shop.setRegistDate(new Date());
        shopRepository.save(shop);
        response.setMessage("注册成功,请使用邮箱和密码登陆！");
        return response;
    }
}
